package Servicios;

import DAO.DAOCarrera;
import DAO.DAOProgramaEducativo;
import Dominio.Carrera;
import Dominio.ProgramaEducativo;
import Dominio.ReticulaAcademica;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class GestorProgramaEducativo extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String sFichero = getServletContext().getRealPath("/");
        sFichero += "/../../web/ServerFiles/archivoReticula.xls";
        File fichero = new File(sFichero);        
        if (fichero.exists()) {
            if(!fichero.delete()){
                System.out.println("Existe un archivo de Reticula Academica en el servidor, será eliminado para proceder con el servicio.");
            }else{
                HashMap<String,String> campos;
                campos = subirArchivo(request, response);
                if(campos!=null){
                    campos.put("ruta", sFichero);
                    registrarProgramaEducativo(request,response,campos);
                    fichero.delete();
                }
            }
        }
        else{
            HashMap<String,String> campos;
            campos = subirArchivo(request, response);
            if(campos!=null){
                campos.put("ruta", sFichero);
                registrarProgramaEducativo(request,response,campos);
                fichero.delete();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private HashMap<String,String> subirArchivo(HttpServletRequest request, HttpServletResponse response) {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        HashMap<String,String> variables;
        variables = new HashMap<String, String>();
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                 List items = upload.parseRequest(request);
                 Iterator iterator = items.iterator();
                 boolean stop = false;
                 while (iterator.hasNext() && !stop) {
                      FileItem item = (FileItem) iterator.next();
                         if (!item.isFormField()) {
                             String fileName = "archivoReticula.xls";
                             String root = getServletContext().getRealPath("/");
                             File path = new File(root + "/../../web/ServerFiles");
                             if (!path.exists()) {
                                 path.mkdirs();
                             }
                             File uploadedFile = new File(path + "/" + fileName);
                             item.write(uploadedFile);
                             stop = true;
                             }else{
                                String variable = item.getFieldName();
                                String valor = item.getString();
                                variables.put(variable, valor);
                            }
                         }
                 return variables;
            } catch (FileUploadException e) {
               e.printStackTrace();
            } catch (Exception e) {
               e.printStackTrace();
            }
           }else{
            return null;
        }
        return null;
    }

    private void registrarProgramaEducativo(HttpServletRequest request, HttpServletResponse response, HashMap<String,String> mapa) {
        PrintWriter out = null;
        String sFichero = mapa.get("ruta");
        int cveCarrera = Integer.parseInt(mapa.get("optcarreras"));
        String nombrePrograma = mapa.get("nombrePE");
        try{    
            response.setContentType("text/html;charset=UTF-8");
            String respuesta = "<p>No fu&eacute; posible registrar el Programa Educativo debido a un problema con el servicio.</p>";
            out = response.getWriter();
            LectorExcelDeReticulaAcademica lectorReticula = new LectorExcelDeReticulaAcademica();
            ReticulaAcademica reticula = lectorReticula.leerReticulaAcademica(sFichero);
            DAOProgramaEducativo daoPrograma = new DAOProgramaEducativo();
            DAOCarrera daoCarrera = new DAOCarrera();
            Carrera carrera = daoCarrera.buscarCarrera(cveCarrera);
            
            if(carrera != null && !nombrePrograma.isEmpty() && reticula != null){
                ProgramaEducativo programa = new ProgramaEducativo(nombrePrograma, carrera, reticula);
                if(daoPrograma.registrarProgramaEducativo(programa)){
                    respuesta = "<p>Programa Educativo registrado con &eacute;xito.</p></br>";
                    respuesta += "<a href=\"PortalAdministrador.jsp\">Regresar</a>";
                }
            }else{                
                System.out.println("Algo salio mal aqui.");
            }
            out.println(respuesta);
        }catch(IOException ex) {
            Logger.getLogger(GestorOfertaAcademica.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

}
